/**
 * Created by yanghaibo on 2016/10/25.
 */
ActivityDetailController = function () {

    // 获取订单详情
    this.getActivityDetail = function(campId, outBizNo) {
        var closeActivityAuth = commonHasAuthCode("app.market.activitymanage.close");
        var serverUrl = App.serverUrl +　"merchantApp/activity/detail.do?campId=" + campId + "&outBizNo=" + outBizNo;
        var sucFunc = function (result) {
            if (result && result.success) {
                // 服务器返回成功
                var activityVo = result.resultObject;
                var controller = new ActivityDetailController();
                controller.formatActivityVo(activityVo);
                activityDetailParam.activityVo = activityVo;
                controller._fixTicketName();
                if (closeActivityAuth && (activityVo.activityStatus == 1 || activityVo.activityStatus == 2)) {
                    CommonUtil.showElement("#activityDetailPage .header .right a");
                } else {
                    CommonUtil.hideElement("#activityDetailPage .header .right a");
                }
                CommonUtil.render($("#activityDetailPage .page-body .ac-info"), "activityDetailHeadTpl", activityVo);
                CommonUtil.render($("#activityDetailPage .page-body .details-page"), "activityDetailTpl", activityVo);
            } else {
                DialogUtil.dialogWarn(result.msg);
            }
        };

        CommonUtil.sendJsonpRequest({
            url: serverUrl,
            success: sucFunc
        });

    };

    // 终止活动
    this.stopActivity = function(campId, outBizNo) {
        var serverUrl = App.serverUrl +　"merchantApp/activity/stop.do?outBizNo=" + outBizNo;
        var sucFunc = function (result) {
            if (result && result.success) {
                // 服务器返回成功
                DialogUtil.dialogWarn("终止成功", function () {
                    var controller = new ActivityDetailController();
                    controller.getActivityDetail(campId, outBizNo);
                });
            } else {
                DialogUtil.dialogWarn(result.msg);
            }
        };

        CommonUtil.sendJsonpRequest({
            url: serverUrl,
            success: sucFunc
        });

    };

    // 查询ROI
    this.queryActivityEffectAnalsysiData = function (campId, outBizNo) {
        activityDetailParam.loading = true; // 渲染图表的时候切换tab会造成图表渲染失败

        var serverUrl = App.serverUrl +　"merchantApp/activity/queryActivityEffectAnalsysiData.do?campId=" + campId + "&outBizNo=" + outBizNo;
        var sucFunc = function (result) {
            if (result && result.success) {
                // 服务器返回成功
                var data = result.resultObject;
                for (var i = 0; i < data.promTools.length; i++) {
                    var promTool = data.promTools[i];
                    if (promTool.voucherType === "MONEY" && promTool.moneyVoucherType == 2 && activityDetailParam.activityVo) {
                        var detailPromTool = activityDetailParam.activityVo.promTools[i];
                        promTool.voucherNameTitle = ActivityUtil.parseVoucherName(detailPromTool || promTool);
                    } else {
                        promTool.voucherNameTitle = ActivityUtil.parseVoucherName(promTool);
                    }
                }
                var _param = this._getOtherLineChartQueryParam(data.activityMarketType);
                if (_param) {
                    data.lineChartTitle = _param.title;
                }
                CommonUtil.render($("#activityDetailPage .page-body .effect-analysis"), "activityDetailAnalysisTpl", data);

                // 渲染饼图
                var elements = document.getElementsByName("detailPagePieChartContainer");
                for (var i = 0; i < elements.length; i++) {
                    var promTool = data.promTools[i];
                    var myChart = echarts.init(elements[i]);
                    var option = activityDetailParam.pieOption;
                    var seriesData = [{
                        value: promTool.sendPrizeCount - promTool.usedCnt,
                        name: "发券数"
                    },{
                        value: promTool.usedCnt,
                        name: "核券数"
                    }];
                    option.series[0].data[0].value = promTool.sendPrizeCount - promTool.usedCnt;
                    option.series[0].data[0].name = "发券数：" + promTool.sendPrizeCount;
                    option.series[0].data[1].value = promTool.usedCnt;
                    option.series[0].data[1].name = "核券数：" + promTool.usedCnt;
                    option.legend.data = ["发券数：" + promTool.sendPrizeCount, "核券数：" + promTool.usedCnt];
                    myChart.setOption(option);
                }
                if (elements.length > 1) {
                    var swiper = new Swiper('#activityDetailPage .swiper-container',{
                        pagination: '#activityDetailPage .swiper-pagination',
                    });
                }


                // 查询活动活动收益
                this.queryActivityIncomeTrendData(campId, outBizNo, 7);
                this.queryActivityOtherTrendData(campId, outBizNo, data.activityMarketType, 7);
            } else {
                DialogUtil.dialogWarn(result.msg);
            }
            activityDetailParam.loading = false;
        };

        CommonUtil.sendJsonpRequest({
            url: serverUrl,
            success: sucFunc.bind(this)
        });
    };

    // 查询活动收益
    this.queryActivityIncomeTrendData = function (campId, outBizNo, days) {

        if (!days) days = 7;
        var serverUrl = App.serverUrl +　"merchantApp/activity/trend/queryActivityIncomeTrendData.do";
        var params = {
            campId: campId,
            outBizNo: outBizNo,
            interval: days
        };
        var sucFunc = function (result) {
            if (result && result.success) {
                // 服务器返回成功
                var data = result.resultObject;
                if (data.length) {
                    var x = []; // x轴数据
                    var yTotal = []; // 总收益
                    var yToday = []; // 今日新增
                    for (var i = 0; i < data.length; i++) {
                        var item = data[i];
                        var month = item.bizDate.substr(4, 2);
                        if (month[0] === "0") {
                            month = month.substr(1);
                        }
                        var date = item.bizDate.substr(6, 2);
                        if (date[0] === "0") {
                            date = date.substr(1);
                        }
                        x.push(month + "-" + date);
                        yToday.push(item.todayCampaignTradeAmt);
                        yTotal.push(item.totalCampaignTradeAmt);
                    }
                    // 收益图渲染
                    var option = activityDetailParam.lineOption;
                    option.legend.data = ["单日收益", "总收益"];
                    option.xAxis[0].data = x;
                    option.yAxis[0].name = "单位：元";
                    option.series = [
                        {
                            name:'单日收益',
                            type:'line',
                            data:yToday
                        },
                        {
                            name:'总收益',
                            type:'line',
                            data:yTotal
                        }
                    ];
                    var myChart = echarts.init(document.getElementById("detailPageIncomeLineChart"));
                    myChart.setOption(option);

                } else {
                    DialogUtil.dialogWarn("数据异常");
                }
            } else {
                DialogUtil.dialogWarn(result.msg);
            }
        };

        CommonUtil.sendJsonpRequest({
            url: serverUrl,
            params: params,
            success: sucFunc
        });
    };

    /**
     * 查询活动特征值
     * @param campId
     * @param outBizNo
     * @param days
     */
    this.queryActivityOtherTrendData = function (campId, outBizNo, activityType, days) {
        var _param = this._getOtherLineChartQueryParam(activityType);
        if (!_param) {
            $("#detailPageLineChart").parent().css("display", "none");
            return;
        }
        if (!days) days = 7;
        var serverUrl = App.serverUrl +　"merchantApp/activity/trend/" + _param.url;
        var params = {
            campId: campId,
            outBizNo: outBizNo,
            interval: days
        };
        var sucFunc = function (result) {
            if (result && result.success) {
                // 服务器返回成功
                var data = result.resultObject;
                if (data.length) {
                    var x = []; // x轴数据
                    var y = []; // y轴数据
                    for (var i = 0; i < data.length; i++) {
                        var item = data[i];
                        var month = item.bizDate.substr(4, 2);
                        if (month[0] === "0") {
                            month = month.substr(1);
                        }
                        var date = item.bizDate.substr(6, 2);
                        if (date[0] === "0") {
                            date = date.substr(1);
                        }
                        x.push(month + "-" + date);
                        y.push(item[_param.key]);
                    }
                    // 收益图渲染
                    var option = activityDetailParam.lineOption;
                    option.legend.data = [_param.legend];
                    option.xAxis[0].data = x;
                    option.yAxis[0].name = _param.unit;
                    option.series = [
                        {
                            name:_param.legend,
                            type:'line',
                            data:y
                        }
                    ];
                    var myChart = echarts.init(document.getElementById("detailPageLineChart"));
                    myChart.setOption(option);

                } else {
                    DialogUtil.dialogWarn("数据异常");
                }
            } else {
                DialogUtil.dialogWarn(result.msg);
            }
        };

        CommonUtil.sendJsonpRequest({
            url: serverUrl,
            params: params,
            success: sucFunc
        });
    };

    this._getOtherLineChartQueryParam = function (activityType) {
        activityType = parseInt(activityType);
        switch (activityType) {
            case 46:
                return {
                    url: "queryNewAddMemberTrendData.do", // 请求url
                    title: "新增会员统计",
                    legend: "新增会员数",
                    key: "todayUsedUserCnt", // 返回值取哪个字段
                    unit: "单位：人"
                };
            case 22:
            case 35:
            case 51:
                return {
                    url: "queryRegularCustomerTrendData.do", // 请求url
                    title: "回头客效果统计",
                    legend: "当日带来回头客数量",
                    key: "todayUsedUserCnt", // 返回值取哪个字段
                    unit: "单位：人"
                };
            case 24:
            case 43:
                return {
                    url: "queryReddemLostCustomerTrendData.do", // 请求url
                    title: "挽回流失会员统计",
                    legend: "挽回流失会员人数",
                    key: "todayUsedUserCnt", // 返回值取哪个字段
                    unit: "单位：人"
                };
            case 25:
                return {
                    url: "queryReddemLostCustomerTrendData.do", // 请求url
                    title: "活动带动消费人次统计",
                    legend: "活动参与人次",
                    key: "todayUsedUserCnt", // 返回值取哪个字段
                    unit: "单位：人"
                };
            case 47:
                return {
                    url: "querySingleSkuMarketEffectTrendData.do", // 请求url
                    title: "单品营销效果统计",
                    legend: "当日活动单品销量",
                    key: "todayUsedCnt", // 返回值取哪个字段
                    unit: "单位：人"
                };
            case 48:
                return {
                    url: "queryNewOpenCardTrendData.do", // 请求url
                    title: "新增开卡会员统计",
                    legend: "活动带来新开卡会员数量",
                    key: "todayUsedCnt", // 返回值取哪个字段
                    unit: "单位：人"
                };
            default:
                return null;
        }
    };

    // 格式化活动对象
    this.formatActivityVo = function(activityDetail) {

        // 活动时间
        if (activityDetail.activityStartTime.indexOf(" ") > 0) {
            activityDetail.activityStartTime = activityDetail.activityStartTime.split(" ")[0];
        }
        if (activityDetail.activityEndTime.indexOf(" ") > 0) {
            activityDetail.activityEndTime = activityDetail.activityEndTime.split(" ")[0];
        }

        // 活动状态
        activityDetail.statusTitle = ActivityUtil.parseActivityStatus2Ch(activityDetail.activityStatus);
        // 发放方式
        activityDetail.obtainTypeTitle = this.obtainType[activityDetail.activityMarketType];
        var campTarget = null;
        if(activityDetail.activityMarketType == 30){//一期的自定义人群
            var  activityConstrain = activityDetail.activityConstrain;

            if (activityConstrain) {
                campTarget = activityConstrain.crowdGroupDesc?constraintModel.crowdGroupDesc:'所有顾客';
            }
        }else if(activityDetail.activityMarketType == 43){//二期的自定义
            var  activityConstrain = activityDetail.activityConstrain;
            if(activityConstrain){
                var crowdModel = activityConstrain.crowdModel;
                campTarget = crowdModel!=null?crowdModel.crowdName:"所有顾客"
            }
        }else{
            campTarget = this.campTargetInfo[activityDetail.activityMarketType];
            campTarget = !campTarget?"":campTarget;
            if(campTarget.indexOf("{") != -1){
                campTarget = campTarget.replace("{replaceValue}",activityDetail.activityTargetCondition);
            }
        }
        activityDetail.campTarget = campTarget;

        for (var i = 0; i < activityDetail.promTools.length; i++) {
            // 发放数量
            if(activityDetail.activityBudget){
                if(activityDetail.promTools[i].promoSendRuleSendnumSelect == 1 || activityDetail.activityBudget.isLimit == "F"){
                    activityDetail.promTools[i].promoSendRuleSendNumTitle = '不限制';
                }else{
                    activityDetail.promTools[i].promoSendRuleSendNumTitle = activityDetail.activityBudget.budgetValue;
                }
            }

            if (activityDetail.promTools[i].voucherType == "MONEY" ) {
                var voucherWorthValue = String(activityDetail.promTools[i].voucherWorthValue);
                if (voucherWorthValue.indexOf(".") > 0) {
                    activityDetail.promTools[i].voucherWorthValueInt = voucherWorthValue.split(".")[0];
                    activityDetail.promTools[i].voucherWorthValueDec = voucherWorthValue.split(".")[1];
                } else {
                    activityDetail.promTools[i].voucherWorthValueInt = voucherWorthValue;
                    activityDetail.promTools[i].voucherWorthValueDec = "00";
                }
            }
            var voucherStartTimeStr=activityDetail.promTools[i].voucherStartTimeStr;
            if (voucherStartTimeStr && voucherStartTimeStr.indexOf(" ") > 0) {
                activityDetail.promTools[i].voucherStartTimeStr = voucherStartTimeStr.split(" ")[0];
                activityDetail.promTools[i].voucherEndTimeStr = activityDetail.promTools[i].voucherEndTimeStr.split(" ")[0];
            }

            if (i === 0) {
                activityDetail.promoSendRuleSendNumTitle = activityDetail.promTools[i].promoSendRuleSendNumTitle;
            }
        }

        //累计领取上限
        if(activityDetail.activityConstrain.userWinCount == 0 || !activityDetail.activityConstrain.userWinCount){
            activityDetail.activityConstrain.userWinCountTitle = "不限制";
        }else{
            activityDetail.activityConstrain.userWinCountTitle = "每人"+activityDetail.activityConstrain.userWinCount+"张";
        }

        //单日领取上限
        if(activityDetail.activityConstrain.userWinFrequencyValue == 0 || !activityDetail.activityConstrain.userWinFrequencyValue){
            activityDetail.activityConstrain.userWinFrequencyTitle = "不限制";
        }else{
            activityDetail.activityConstrain.userWinFrequencyTitle = "每人"+activityDetail.activityConstrain.userWinFrequencyValue+"张";
        }

        // 投放渠道
        var couldShowChannels = ['SHOP_DETAIL', 'A_PAY_CODE', 'POS', 'COMMISSION_SETTING', 'QR_CODE'];
        for (var i = activityDetail.publishChannels.length - 1; i >= 0; i--) {
            var publishChannel = activityDetail.publishChannels[i];
            if (couldShowChannels.indexOf(publishChannel.publishChannelType) === -1) {
                activityDetail.publishChannels.splice(i, 1);
            }
        }

    };

    // 修正券核销数据中全名称
    this._fixTicketName = function() {
        if (activityDetailParam.activityVo.activityMarketType == 47) {
            for (var i = 0; i < activityDetailParam.activityVo.promTools.length; i++) {
                var promTool = activityDetailParam.activityVo.promTools[i];
                var voucherName = promTool.voucherNameTitle = ActivityUtil.parseVoucherName(promTool);
                $("#activityDetailPage .swiper-wrapper .swiper-slide").eq(i).find(".c-legend li").html('<i class="zhk-list_quan"></i>' + voucherName);
            }
        }
    };

    // 活动对象
    this.campTargetInfo = {
        21:'所有到店消费的会员',
            22:'所有顾客',
            23:'单笔消费满{replaceValue}元的会员',
            24:'{replaceValue}天没有到店消费的会员',
            25:'所有顾客',
            26:'所有会员',
            27:'所有会员',
            28:'最近7天过生日的会员',
            29:'消费总次数低于{replaceValue}次的会员',
            30:'',//取冗余的名称
            31:'30天以上未到店消费的会员',
            32:'近30天低于2次消费的会员',
            33:'本月生日会员',
            34:'所有顾客',
            35:'所有顾客',
            36:'轻度流失会员',
            37:'所有顾客',
            38:'生日会员',
            39:'低消费常客',
            40:'住在附近的会员',
            41:'高消费散客',
            42:'忠实会员',
            43:'',//取人群组名称
            44:'集点卡',
            45:'集点卡发奖',
            46:'从未到店消费的顾客',
            47:'所有顾客',
            48:'活动创建后的新开卡用户'
    };

    this.obtainType = {
        46:'顾客在投放渠道领券',//新会员招募
            22:'消费后自动发放至会员卡券包',//消费送券
            25:'顾客扫码后领取',//扫码送券
            47:'顾客在投放渠道领券',//单品营销
            43:'顾客在投放渠道领券',//自定义人群活动
            48:'顾客在开卡成功页面领取',//开卡关怀
            51:'消费后自动发放至会员卡券包'//消费送圈人活动
    };
};